package com.smart.order.listener;

import com.smart.order.dto.OrderDto;
import com.smart.order.dto.OrderLog;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;

@RocketMQTransactionListener
@Slf4j
public class OrderMessageTransactionListener implements RocketMQLocalTransactionListener {

    /**
     * 执行本地事务
     *
     * @param msg
     * @param arg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        // 获取消息中的数据
        OrderDto payload = (OrderDto) msg.getPayload();
        // 执行本地数据库操作

        // 创建事务记录表  方便消息回查
//         订单ID
        return RocketMQLocalTransactionState.UNKNOWN;
    }

    /**
     * 消息回查
     * 事务日志表
     *
     * @param msg
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        //
        OrderDto orderDto = (OrderDto) msg.getPayload();
        String orderSn = orderDto.getOrderSn();
        // 执行事务记录表
        OrderLog orderLog = new OrderLog();
        return orderLog != null ? RocketMQLocalTransactionState.COMMIT : RocketMQLocalTransactionState.ROLLBACK;

    }
}
